import { use, useState, Suspense } from "react";
import PropTypes from 'prop-types'
function fetchSearchData(keyword) {
    const controller = new AbortController();
    const promise = fetch(`http://localhost:3000/search?keyword=${keyword}`, {
        signal: controller.signal
    })
        .then(res => res.json())
        .catch(() => [])
    promise.controller = controller;
    return promise;
}
function SearchResults({ promise }) {
    const results = use(promise);
    return (
        <ul>
            {
                results.map((item, index) => (
                    <li key={index}>{item}</li>
                ))
            }
        </ul>
    )
}
SearchResults.propTypes = {
    promise: PropTypes.string.isRequired
}
function App() {
    const [searchPromise, setSearchPromise] = useState(null);
    const [keyword, setKeyword] = useState('');
    const handleSearch = (keyword) => {
        if (searchPromise?.controller) {
            searchPromise?.controller.abort();
        }
        setKeyword(keyword);
        setSearchPromise(keyword.trim() ? fetchSearchData(keyword) : null);
    }
    return (
        <div>
            <h2>搜索建议</h2>
            <input
                type="text"
                value={keyword}
                onChange={(event) => handleSearch(event.target.value)}
                placeholder="请输入关键字"
            />
            {
                searchPromise && (
                    <Suspense fallback={<div>正在搜索{keyword}...</div>}>
                        <SearchResults promise={searchPromise} />
                    </Suspense>
                )
            }
        </div>
    )

}
export default App;